package cn.tedu.jxc.aop;

import cn.tedu.jxc.pojo.entity.Log;
import cn.tedu.jxc.security.LoginPrincipal;
import cn.tedu.jxc.service.LogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
@AllArgsConstructor
public class LogAspect {
    public LogAspect(){
        log.debug("创建切面对象：TimerAspect");
    }
    @Autowired
    private LogService logService;
    @Pointcut("@annotation(cn.tedu.jxc.aop.LogAnnotation)")
    public void pt(){

    }

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp)throws Throwable{
       long startTime = System.currentTimeMillis();
       MethodSignature signature = (MethodSignature) pjp.getSignature();
       Method method = signature.getMethod();
        log.debug("执行了{}}方法",method);
       Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       LoginPrincipal loginPrincipal = (LoginPrincipal)principal;
       LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
       Log logs = new Log();
       logs.setMethod(annotation.operator());
       logs.setUsername(loginPrincipal.getUsername());
       logs.setStatus(annotation.module());

       //执行方法
       try {
           return pjp.proceed();
       }catch (Exception exception){
           log.error(exception.getMessage());
           logs.setError(exception.getMessage());
           throw exception;
       }finally {
           long time = System.currentTimeMillis()-startTime;
           logs.setTime(time);
           logService.addLogInfo(logs);
       }

   }
}
